﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DataLib.Accounts.Bus;
using DataLib.Common;

namespace Ewts.Storage
{
    public partial class InWrl : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                User curUser = new DataLib.Accounts.Bus.User();
                if (Session["UserInfo"] != null)
                {

                    curUser = (User)Session["UserInfo"];
                    if (curUser.UserType == "AD")
                    {
                        this.hidgraphic.Value = "";
                    }
                    else
                    {
                        hidgraphic.Value = curUser.CompanyCity;
                    }
                    HiddenOper.Value = curUser.UserName;
                }
                else
                {
                    Response.Redirect("/Accounts/Login.aspx");
                    return;
                }
                bindMonth();
                if (Request["insid"] != null && Request["insid"].ToString().Trim() != "" && Request["insid"].ToString().Trim() != "0")
                {
                    int insid = int.Parse(Request["insid"].ToString().Trim());
                    DataLib.Model.InStorage model = new DataLib.BLL.InStorage().GetModel(insid);
                    txtRemark.Value = model.remark;
                    if (model.outid > 0)
                    {
                       
                        if (curUser.UserName == "admin" || model.remark == null || model.remark.Trim() == "")
                        {
                            txtRemark.Disabled = false;
                        }
                        else
                        {
                            chkHardTest.Enabled = false;
                            txtRemark.Disabled = true;
                        }
                        bindOutid(model.outid.ToString());
                    }
                    else
                    {
                        DataLib.BLL.Hardware bh = new DataLib.BLL.Hardware();
                        if (bh.IsHardCheck((int)model.id) == true)
                        {
                            chkHardTest.Checked = true;
                        }
                        if (curUser.UserName == "admin")
                        {
                            chkHardTest.Enabled = true;
                        }
                        else
                        {
                            chkHardTest.Enabled = false;
                        }
                        bindData(model.cjoid.ToString());
                    }
                }
                else if (Request["cjoid"] != null && Request["cjoid"].ToString().Trim() != "0")
                {
                    bindData(Request["cjoid"].ToString().Trim());
                }
                else if (Request["outid"] != null && Request["outid"].ToString().Trim() != "0")
                {
                    bindOutid(Request["outid"].ToString());
                }
            }
        }
        /// <summary>
        /// 根据cjoid绑定列表
        /// </summary>
        protected void bindData(string cjoid)
        {

            //根据cjoid取得入库单号
            int instroageid = new DataLib.BLL.BarCode().GetInStroageIDByCjoid(cjoid);
            if (instroageid != 0)
            {
                //已经称过重
                DataLib.Model.InStorage insModel = new DataLib.BLL.InStorage().GetModel(instroageid);
                txtRemark.Value = insModel.remark;
                if (HiddenOper.Value != "admin" && txtRemark.Value.Trim() != "")
                {
                    txtRemark.Disabled = true;
                }
                txtIn.Value = insModel.wrlno;
                hidInStoID.Value = insModel.id.ToString();
                if (insModel.islock)
                    chkAllLock.Checked = true;
                else
                    chkAllLock.Checked = false;
                hidInDepart.Value = insModel.InDepart;
                hidOutDepart.Value = insModel.OutDepart;
                labInDate.InnerHtml = ((DateTime)insModel.instoragetime).ToString("yyyy-MM-dd hh:mm");
                if (insModel.clearingmonth != null && insModel.clearingmonth.Length == 6)
                {
                    string stryear = insModel.clearingmonth.Substring(0, 4);
                    string strmonth = insModel.clearingmonth.Substring(4, 2);
                    dropYear.SelectedValue = stryear;
                    dropMonth.SelectedValue = strmonth;
                }
                DataTable dt = new DataLib.BLL.BarCode().GetList("InStrorageID=" + instroageid.ToString().Trim()).Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    rept.DataSource = dt;
                    rept.DataBind();
                }
            }
            else
            {
                //未称过重
                hidInStoID.Value = "0";
                //string strInLeft = "";
                //strInLeft += "M";
                DataLib.Model.Cjo cModel = new DataLib.BLL.Cjo().GetModel(int.Parse(cjoid));
                hidInDepart.Value = cModel.belogcity;
                hidOutDepart.Value = cModel.graphiccity;
                //txtIn.Value = Code.NumGeneration.GetSerialNum(strInLeft, "WRL");
            }

            SetDisplay(int.Parse(cjoid), 1);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            /*提交事件 
             * barcode status : 
             *      1 入临时库      2 临时库出库     3 分类入库      4 分类出库      5 半成品入库
             *      6 半成品出库    7 成品入库       8 成品出库      9 移库 入库     10 移库出库
             */


            //如果是普通称重  如果是移库称重
            if (hidInStoID.Value == "" || hidInStoID.Value == "0")
            {
                MessageBox.Show(this, "不能提交空的收集清单");
                return;
            }


            int wrlid = SubmitInWrl(HiddenOper.Value);
            if (wrlid != 0)
            {
                DataLib.Common.MessageBox.ShowAndRedirect(Page, "保存成功！", "/RDLC/WRLInfoRDLC.aspx?wrlid=" + wrlid.ToString());
                HardInsert(wrlid);
            }
        }

        protected void SetDisplay(int id, int flag)
        {
            DataLib.Model.CJOItem cjoModel = new DataLib.Model.CJOItem();
            DataLib.BLL.CJOItem cjoBll = new DataLib.BLL.CJOItem();
            DataLib.Model.LoadNum lmodel = null;

            ///临时库入库
            if (flag == 1 && id > 0) // cjo
            {
                //cjoid = Request["cjoid"].ToString().Trim();
                cjoModel = cjoBll.GetListByCid(id);
                BindVehiclePlage(id, 'c');
                hidCJOID.Value = id.ToString();
                inputLoadNum.Value = cjoModel.loadnumno;
                inputCjo.Value = cjoModel.cjono;
                hidLoadID.Value = cjoModel.loadnumid.ToString();
                txtcutomer.Value = cjoModel.companyname;
                txtpeculiarrequire.Value = cjoModel.peculiarrequire;
            }
            else if (flag == 2 && id > 0)
            {
                DataLib.Model.OutStorage outModel = new DataLib.BLL.OutStorage().GetModel(id);
                string loadno = outModel.VLoadNum;
                if (loadno != null && loadno.Substring(0, 2) == "86")
                {
                    lmodel = new DataLib.BLL.LoadNum().GetLoadID(loadno);
                    txtcutomer.Value = lmodel.cumname;
                }
                else
                {
                    DataLib.Model.Vload vlModel = new DataLib.BLL.Vload().GetModelByOutID(id);
                    if (vlModel != null)
                    {
                        txtcutomer.Value = vlModel.inscumname;

                        hidLoadID.Value = "0";
                    }
                    // txtcutomer.Value = outModel.inDepart + "伟翔";
                }
                inputCjo.Value = outModel.outStorageNo;
                hidoutparID.Value = id.ToString();


                BindVehiclePlage((int)outModel.id, 'o');
            }

            User curUser = new User();
            curUser = (User)Session["UserInfo"];
            HiddenOper.Value = curUser.UserName;

        }



        /// <summary>
        /// 绑定车牌号及收货员
        /// </summary>
        /// <param name="cjoid">CJO单的ID号</param>
        protected void BindVehiclePlage(int id, char flag)
        {
            DataLib.Model.VehicleArrange vamodel = new DataLib.Model.VehicleArrange();
            DataLib.BLL.VehicleArrange vabll = new DataLib.BLL.VehicleArrange();
            if (flag == 'c')
            {
                vamodel = vabll.GetModelByCjoid(id);
            }
            else
            {
                vamodel = vabll.GetModelByOutid(id);
            }
            if (vamodel != null)
            {
                vamodel.status = 0;
                //车牌绑定
                string[] arrplate = vamodel.platenumberid.Split(',');
                string[] sarr = vamodel.sealno.Split('@');
                int i = 0;
                for (i = 0; i < arrplate.Length; i++)
                {
                    if (arrplate[i] != null && arrplate[i].ToString().Trim() != "")
                    {
                        int plateid = int.Parse(arrplate[i]);
                        DataLib.Model.PlateNumber platemodel = new DataLib.BLL.PlateNumber().GetModel(plateid);
                        string plateNumInfo = platemodel.plateno;
                        foreach (string strseal in sarr)
                        {
                            if (strseal != null && strseal.IndexOf(":") > 0)
                            {
                                string[] arrseal = strseal.Split(':');
                                if (arrplate[i] == arrseal[0] && arrseal.Length > 1)
                                {
                                    plateNumInfo += "-";
                                    plateNumInfo += arrseal[1];
                                    break;
                                }
                            }
                        }
                        ListItem listitem = new ListItem(plateNumInfo, platemodel.id.ToString());
                        dropPlate.Items.Add(listitem);
                        dropPlate.DataBind();
                    }
                }

                //收货员操作
                string[] arrvehider = vamodel.vehiderid.Split(',');
                string vehider = "";
                for (i = 0; i < arrvehider.Length; i++)
                {
                    if (arrvehider[i] != null && arrvehider[i].ToString().Trim() != "")
                    {
                        int vehiderid = int.Parse(arrvehider[i]);
                        DataLib.Model.Vehiclor vehmodel = new DataLib.BLL.Vehiclor().GetModel(vehiderid);
                        vehider += vehmodel.name + ",";

                    }
                }
                txtvehider.Value = vehider;
            }
        }



        /// <summary>
        /// 根据cjoid对派车状态进行改变
        /// </summary>
        /// <param name="cjoid">CJO单的ID号</param>
        protected void SetVehicleArrange(int cjoid)
        {
            DataLib.Model.VehicleArrange vamodel = new DataLib.BLL.VehicleArrange().GetModelByCjoid(cjoid);

            //派车操作
            if (vamodel != null && vamodel.status == 1)
            {
                vamodel.status = 0;

                //string[] arrplate = vamodel.platenumberid.Split(',');
                int i = 0;
                //for (i = 0; i < arrplate.Length; i++)
                //{
                //    if (arrplate[i] != null && arrplate[i].ToString().Trim() != "")
                //    {
                //        int plateid = int.Parse(arrplate[i]);
                //        DataLib.Model.PlateNumber platemodel = new DataLib.BLL.PlateNumber().GetModel(plateid);
                //        platemodel.currentstatus--;
                //        new DataLib.BLL.PlateNumber().Update(platemodel);
                //    }
                //}

                //收货员操作
                string[] arrvehider = vamodel.vehiderid.Split(',');
                for (i = 0; i < arrvehider.Length; i++)
                {
                    if (arrvehider[i] != null && arrvehider[i].ToString().Trim() != "")
                    {
                        int vehiderid = int.Parse(arrvehider[i]);
                        DataLib.Model.Vehiclor vehmodel = new DataLib.BLL.Vehiclor().GetModel(vehiderid);
                        vehmodel.currentstatus--;
                        new DataLib.BLL.Vehiclor().Update(vehmodel);
                    }
                }

                vamodel.status = 0;


                new DataLib.BLL.VehicleArrange().Update(vamodel);//派车状态结束
            }
        }

        /// <summary>
        /// 根据CJO的ID绑定临时入库数据列表
        /// </summary>
        protected void BindDataByCjoid(string cjoid)
        {
            DataTable dt = new DataTable();
            rept.DataSource = dt;
            rept.DataBind();
        }

        protected string GetIsLock(string islock)
        {
            if (Boolean.Parse(islock))
                return "checked";
            else
                return "";
        }

        /// <summary>
        /// 移库称重
        /// </summary>
        /// <param name="outid"></param>
        protected void bindOutid(string outid)
        {
            DataLib.Model.OutStorage outModel = new DataLib.BLL.OutStorage().GetModel(int.Parse(outid));
            inputLoadNum.Value = outModel.VLoadNum;
            hidInDepart.Value = outModel.belogarea;
            hidOutDepart.Value = outModel.graphicCity;
            hidOutWeight.Value = outModel.totalWeight.ToString();

            //if (outModel.StorageType == "原料库" || outModel.inDepart != outModel.belogarea)
            //{
            trjxwc.Visible = true;
            txtMechanerr.Visible = true;
            lblOuttotal.Visible = true;
            lblOuttotal.InnerText = outModel.totalWeight.ToString();
            // }
            string cjoid = "0";
            string loadnumid = "0";
            DataLib.BLL.InStorage insBll = new DataLib.BLL.InStorage();

            DataTable dtins = insBll.GetList("outid=" + outid).Tables[0];
            //已经移库称重
            if (dtins != null && dtins.Rows.Count > 0)
            {
                int instroageid = int.Parse(dtins.Rows[0]["id"].ToString());
                DataLib.Model.InStorage insModel = insBll.GetModel(instroageid);
                tdinsweight.InnerText = insBll.GetInsTotalWeight((int)insModel.id).ToString();
                hidInStoID.Value = instroageid.ToString();
                txtMechanerr.Value = insModel.mechanerr.ToString();
                txtIn.Value = insModel.wrlno;
                if (insModel.islock)
                    chkAllLock.Checked = true;
                else
                    chkAllLock.Checked = false;
                labInDate.InnerHtml = ((DateTime)insModel.instoragetime).ToString("yyyy-MM-dd hh:mm");
                DataTable dt = new DataLib.BLL.BarCode().GetList("InStrorageID=" + instroageid.ToString().Trim()).Tables[0];
                txtRemark.Value = insModel.remark;
                if (HiddenOper.Value != "admin" && txtRemark.Value.Trim() != "")
                {
                    txtRemark.Disabled = true;
                }
                if (insModel.clearingmonth != null && insModel.clearingmonth.Length == 6)
                {
                    string stryear = insModel.clearingmonth.Substring(0, 4);
                    string strmonth = insModel.clearingmonth.Substring(4, 2);
                    dropYear.SelectedValue = stryear;
                    dropMonth.SelectedValue = strmonth;
                }
                if (dt != null && dt.Rows.Count > 0)
                {
                    rept.DataSource = dt;
                    rept.DataBind();
                }
            }
            else
            {
                //string strInLeft = "";
                //strInLeft += "M";
                //txtIn.Value = Code.NumGeneration.GetSerialNum(strInLeft, "WRL");
            }
            hidCJOID.Value = cjoid;
            hidLoadID.Value = loadnumid;
            hidOutid.Value = outid;


            SetDisplay(int.Parse(outid), 2);

        }

        //称重提交事件
        protected int SubmitInWrl(string man)
        {
            DataLib.BLL.InStorage bllIn = new DataLib.BLL.InStorage();
            DataLib.Model.InStorage inModel = new DataLib.Model.InStorage();
            DataLib.BLL.VehicleArrange bllVA = new DataLib.BLL.VehicleArrange();
            DataLib.Model.VehicleArrange vaModel = new DataLib.Model.VehicleArrange();
            DataLib.BLL.OutStorage bllOut = new DataLib.BLL.OutStorage();

            inModel = bllIn.GetModel(int.Parse(hidInStoID.Value));
            //inModel.remark = txtRemark.Value;
            if (inModel.outid != 0 && inModel.outid != null)
            {
                vaModel = bllVA.GetModelBySrcid(hidOutid.Value, 0);
                DataLib.Model.OutStorage oModel = bllOut.GetModel((int)inModel.outid);
                decimal tweight = bllIn.GetInsTotalWeight((int)inModel.id) + (decimal)inModel.mechanerr;
                //if (tweight < 0) {
                //    DataLib.Common.MessageBox.ResponseScript(Page, "alert('机械误差不合法');$('.txtMechanerr').val('');");
                //    return 0;
                //}
                //if (tweight > oModel.totalWeight)
                //{
                //    DataLib.Common.MessageBox.ResponseScript(Page, "alert('超出出库单重量，请重新输入');$('.txtMechanerr').val('');");
                //    //DataLib.Common.MessageBox.Show(Page, "超出出库单重量，请重新输入");
                //    return 0;
                //}
                oModel.currentWeight = tweight;
                if (oModel.currentWeight == oModel.totalWeight)
                {
                    oModel.status = 0;
                }

                bllOut.Update(oModel);
                bllIn.Update(inModel);
                string month = dropYear.SelectedValue + dropMonth.SelectedValue;
                bllIn.InstorageSubmit((int)inModel.id, "5", month);
            }
            else
            {
                //vaModel = bllVA.GetModelBySrcid(hidCJOID.Value, 0);
                string month = dropYear.SelectedValue + dropMonth.SelectedValue;
                //bllIn.Update(inModel);
                int flag = bllIn.InstorageSubmit((int)inModel.id, "0", month);
                inModel.id = flag;


            }

            return (int)inModel.id;
        }

        protected void bindMonth()
        {
            int year = DateTime.Now.Year;

            ListItem listitem = new ListItem((year + 1).ToString() + "年", (year + 1).ToString());
            dropYear.Items.Add(listitem);
            listitem = new ListItem(year.ToString() + "年", year.ToString());
            dropYear.Items.Add(listitem);
            listitem = new ListItem((year - 1).ToString() + "年", (year - 1).ToString());
            dropYear.Items.Add(listitem);

            dropYear.SelectedValue = year.ToString();
            dropMonth.SelectedValue = DateTime.Now.Month.ToString().PadLeft(2, '0');

        }

        /// <summary>
        /// 是否硬件测试
        /// </summary>
        /// <returns></returns>
        private bool HardInsert(int wrlid)
        {
            DataLib.BLL.Hardware bll = new DataLib.BLL.Hardware();
            return bll.HardInsert(wrlid, chkHardTest.Checked);
        }

    }
}